<script lang="ts" setup>
import HeaderMenu from "@/components/HeaderMenu.vue";
import SearchGoods from "@/components/SearchGoods.vue";
import FooterComponent from "@/components/FooterComponent.vue";
import {getGoodsList,getGoodsInfo} from "@/api/goods.js";
import {setSeckill,getSeckill} from '@/api/seckill'
import {onMounted, onUnmounted, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import {Stomp} from "@stomp/stompjs";
import SockJS from "sockjs-client";
onMounted(()=>{
  getGoodsListData()
  isRootFun()
})

const isRoot = ref(false)
const isRootFun = ()=>{
  if (localStorage.getItem('root') == 'root') {
    isRoot.value = true
  }
}
const goodsData = ref({})
const getGoodsListData = async () => {
  let result = await getGoodsList()
  if (result.data.code === 200) {
    goodsData.value = result.data.data
    console.log(goodsData.value)
    goodsData.value.goods1.forEach(item=>{
      options01.value.push({
        value: item.gid,
        label: item.gname,
      })
    })
    goodsData.value.goods2.forEach(item=>{
      options01.value.push({
        value: item.gid,
        label: item.gname,
      })
    })
    goodsData.value.goods3.forEach(item=>{
      options01.value.push({
        value: item.gid,
        label: item.gname,
      })
    })
    goodsData.value.goods4.forEach(item=>{
      options01.value.push({
        value: item.gid,
        label: item.gname,
      })
    })
  }
}

//选择器
const seckillGoodsId = ref()
const options01 = ref([])
const isSeckill = ref(false)
const seckillNum = ref(100)
const handleChange = (value: number) => {
  console.log(value)
}
//监听秒杀商品id的变化
const currentGoodsInfo = ref({})
watch(seckillGoodsId, async (newValue, oldValue) => {
  isSeckill.value = true
  console.log(newValue)
  let result = await getGoodsInfo(newValue)
  if (result.data.code === 200){
    currentGoodsInfo.value = result.data.data
    console.log(currentGoodsInfo.value)
  }
})

const startSeckillFun = async ()=>{
  console.log(seckillGoodsId.value,seckillNum.value)
  let result = await setSeckill(seckillGoodsId.value,seckillNum.value)
  if (result.data.code == 200) {
    ElMessage.success("发布秒杀活动成功")
    console.log(result.data.data)
  }else {
    ElMessage.error("发布秒杀活动失败")
  }
}
//发送秒杀请求
const startSeckill = async ()=>{
  let result = await getSeckill(seckillGoodsId.value)
  console.log(result.data.data)
  console.log(result)
  if (result.data.code == 200) {
    if (result.data.data == 'success') {
      ElMessage.success(result.data.msg)
    }else if (result.data.data == 'failed'){
      ElMessage.warning(result.data.msg)
    }else if (result.data.data == 'end'){
      ElMessage.info(result.data.msg)
    }
  }else {
    ElMessage.error(result.data.msg)
  }
}

//websocket消息提醒
/*const message = ref('');
let socket;
const isReceiveMsg = ref(false)
const connectWebSocket = ()=>{
  if ('WebSocket' in window) {
    // 创建 WebSocket 连接
    socket = new WebSocket('ws://localhost:5000/user/notifyToUser');
    // socket = new WebSocket('ws://localhost:5000/mywebsocket/websocketSeckill');
    // socket = new WebSocket('ws://localhost:9100/websocketSeckill');
    // 当 WebSocket 连接打开时执行
    socket.onopen = () => {
      console.log('WebSocket 连接已打开');
    };

    // 当接收到消息时更新 message
    socket.onmessage = (event) => {
      message.value = event.data;
      console.log('收到消息:', event.data)
      isReceiveMsg.value = true
      ElMessage.info("你收到一条秒杀活动的提醒，请前往秒杀抢购")
    };

    // 当 WebSocket 连接关闭时执行
    socket.onclose = () => {
      console.log('WebSocket 连接已关闭');
    };

    // 当 WebSocket 连接发生错误时执行
    socket.onerror = (error) => {
      console.error('WebSocket 连接发生错误:', error);
    };
  }else {
    console.error('WebSocket 不支持')
  }
}
onMounted(() => {
  connectWebSocket()
});

onUnmounted(() => {
  // 组件销毁时关闭 WebSocket 连接
  if (socket) {
    socket.close();
  }
});*/
// SSE
/*const messageGoodsId = ref()

const eventSource = new EventSource('http://localhost:5000/user/subscribe');
eventSource.onmessage = function (event) {
  console.log('Message from server:', event.data);
  isReceiveMsg.value = true
  ElMessage.info("你收到一条秒杀活动的提醒，请前往秒杀抢购")
  // messageGoodsId.value = parseInt(event.data,10)
  let dataStr = event.data.trim(); // 去除前后的空格
  let parsedNumber = parseInt(dataStr, 10); // 使用 parseInt 将字符串转换为整数
  if (isNaN(parsedNumber)) {
    console.error("Failed to convert to number:", dataStr);
    console.log(parsedNumber)
  } else {
    messageGoodsId.value = parsedNumber;
  }
  console.log(messageGoodsId.value)

/!*  let result = await getGoodsInfo(messageGoodsId.value)
  if (result.data.code === 200) {
    currentGoodsInfo.value = result.data.data
    console.log("接收到消息之后的信息：")
    console.log(currentGoodsInfo.value)
  }*!/
};

eventSource.onerror = function(err) {
  console.error('EventSource failed:', err);
};*/

//stomp
/*let stompClient = null;

const connect = () => {
  const socket = new SockJS('http://localhost:5000/websocketSeckill');
  stompClient = Stomp.over(socket);

  stompClient.connect({}, (frame) => {
    console.log('Connected: ' + frame);
    stompClient.subscribe('/topic/seckill', (message) => {
      console.log(message.body);
    });
  }, (error) => {
    console.error('STOMP error: ', error);
  });
};

onMounted(() => {
  connect();
});

onUnmounted(() => {
  if (stompClient) {
    stompClient.disconnect();
  }
});*/
</script>

<template>
  <div>
    <HeaderMenu></HeaderMenu>
    <SearchGoods></SearchGoods>

    <div class="seckill-content">
      <el-card style="max-width: 350px">
        <template #header>
          <el-button color="#626aef" @click="startSeckill" :disabled="!isSeckill">抢购商品</el-button>
          <span>{{currentGoodsInfo.gname}}</span>
        </template>
        <img
            v-if="isSeckill"
            :src="currentGoodsInfo.gremain"
            style="width: 300px;height: 300px;"
        />
        <img
            v-else
            src="@/assets/img/user-consumer/jingmao.png"
            style="width: 300px;height: 300px;"
        />
      </el-card>
      <div>
        <p>请选择需要秒杀的商品和数量</p>
        <el-select
            v-model="seckillGoodsId"
            placeholder="请选择需要秒杀的商品"
            size="large"
            style="width: 240px"
        >
          <el-option
              v-for="item in options01"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <div v-show="isRoot" class="isRoot-div">
          <el-input-number v-model="seckillNum" :min="1" :max="1000" @change="handleChange" />
          <el-button color="#626aef" @click="startSeckillFun" >发布秒杀活动</el-button>
        </div>
      </div>

    </div>

    <FooterComponent class="footerComponent"></FooterComponent>
  </div>
</template>

<style scoped>
.isRoot-div {
  margin: 20px;
  box-sizing: border-box;
}
.footerComponent {
  position: absolute;
  bottom: 0;
  width: 100%;
}
.seckill-content {
  display: flex;
}
</style>
